package common

import (
	"crypto/hmac"
	"crypto/md5"
	"crypto/sha256"
	"encoding/hex"
	"hash"

	"github.com/spf13/viper"
	"golang.org/x/crypto/ripemd160"
)

func GetEncryptPassword(password, salt string) string {
	return Md5(Md5(password) + salt)
}

func Md5(str string) string {
	hashs := md5.New()
	hashs.Write([]byte(str))
	return hex.EncodeToString(hashs.Sum(nil))
}

/*GetEncryptedToken
 * 获取加密后的Token
 * @param string $Token Token标识
 * @return string
 */
func GetEncryptedToken(token string) string {
	hashalgo := viper.GetString("token.hashalgo")
	key := viper.GetString("token.key")
	return HashHmac(hashalgo, token, key)
}

func HashHmac(algo, data, key string) string {
	var m hash.Hash
	dataByte := []byte(data)
	keyByte := []byte(key)
	switch algo {
	case "sha256":
		m = hmac.New(sha256.New, keyByte)
	case "ripemd160":
		m = hmac.New(ripemd160.New, keyByte)
	default:
		panic("未定义加密类型")
	}
	_, _ = m.Write([]byte(dataByte))
	result := m.Sum(nil)
	return hex.EncodeToString(result)
}
